<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-row :gutter="2">
      <el-col :span="4" :offset="2"><el-button type="primary" @click="batchSaveStudentSubmit">提交保存<i class="el-icon-edit el-icon--right"></i></el-button></el-col>
    </el-row>
    <el-row  :gutter="20">
      <el-col :span="3"><label>学生总数:</label></el-col>
      <el-col :span="2"><span>{{number}}</span></el-col>
    </el-row>
    <el-table :data="tableData" border highlight-current-row style="width: 80%;margin:20px auto;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { batchSaveStudent } from '@/api/student'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: [],
      number: 0
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      this.number = this.tableData.length
    },
    batchSaveStudentSubmit() {
      const tableData = this.tableData
      batchSaveStudent(tableData).then(response => {
        this.$router.push({ path: '/student/student-all/' })
      })
    }
  }
}
</script>
